package com.cicadamob.contact.api.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Handler;

import com.cicadamob.contact.api.Utils.pinyin.PinyinTools;

/**查找所以手机联系人
 * @author Administrator
 *
 */
public class FindAllSysContactRunnable implements Runnable {
	private Handler mHandler;
	private Context mContext;
	private int what;
	private boolean OnlyNeedInstalled=false;
	private boolean isCommon = false;
    public FindAllSysContactRunnable(Handler mHandler,Context mContext,int what){
    	this.mHandler=mHandler;
    	this.mContext=mContext;
    	this.what=what;
    }
    public FindAllSysContactRunnable(Handler mHandler,Context mContext,int what,boolean OnlyNeedInstalled,boolean isCommon){
    	this.mHandler=mHandler;
    	this.mContext=mContext;
    	this.what=what;
    	this.isCommon = isCommon;
    	this.OnlyNeedInstalled=OnlyNeedInstalled;
    }
	@Override
	public void run() {
		List<Contact> result=null;
		if(!OnlyNeedInstalled){
			if(isCommon){
				result=APPContactDao.getCommonContactWithAllPhone(mContext);
				if(result==null){
					result = CommonCompanyContactDao.getComanyCommonContact(mContext);
				}else{
					result.addAll(CommonCompanyContactDao.getComanyCommonContact(mContext));
				}
			}else{
				result=APPContactDao.getContactWithAllPhone(mContext);
			}
		}else{
			result=new ArrayList<Contact>();
			Map<String, String> installList=APPContactDao.getInstallPhone(mContext);
			for (String key : installList.keySet()) {
				Contact cc = new Contact();
				cc.setDisplayName(installList.get(key)==null?key:installList.get(key));
				cc.setLinkPhone(key);
				cc.setInstall(1);
				String letter=PinyinTools.getShouPinYin(cc.getDisplayName().substring(0, 1));
				char[] firstChar= letter.toCharArray();
				if(firstChar!=null&&firstChar.length>0){
					if(firstChar[0]>='a'&&firstChar[0]<='z'){
							cc.setLetter(letter.toUpperCase());
					}else if(firstChar[0]>='A'&&firstChar[0]<='Z'){
						cc.setLetter(letter);
					}else{
						cc.setLetter("#");
					}
				}else{
					cc.setLetter("#");
				}
				
				cc.setFirstPy(PinyinTools.getFirstCharPinYin(cc.getDisplayName()));
				cc.setAllPy(PinyinTools.getAllPinYin(cc.getDisplayName()));
				cc.setSort(PinyinTools.getSort(cc.getDisplayName()));
				result.add(cc);
			}
		}
//		Collections.sort(result, new Comparator<Contact>() {
//
//			@Override
//			public int compare(Contact arg0, Contact arg1) {
//				// TODO Auto-generated method stub
//				return arg0.compareTo(arg1);
//			}
//		});
		
		mHandler.obtainMessage(what, result).sendToTarget();
	}

}
